/*
 * Encoder class for privateMessage
 */
package ws.websk.chatEndpoint2;

import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import ws.websk.chatEndpoint2.messages.UsersListMessage;

/**
 * @author Jens-Marius Nergård Hansen
 */
public class UsersListMsgEncoder implements Encoder.Text<UsersListMessage> {

    @Override
    public String encode(UsersListMessage object) throws EncodeException {
        //Build an jsonArray with nicknames
        JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
        for(String nickname:object.getUsersList())
            jsonArrayBuilder.add(nickname);
        
        //Add parameters to a jsonObject
        JsonObject jsonObject = Json.createObjectBuilder()
                .add("type", object.getType())
                .add("userslist", jsonArrayBuilder.build())
                .build();

        StringWriter stWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(stWriter);
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();

        String jsonData = stWriter.toString();
        return jsonData;
    }

    @Override
    public void init(EndpointConfig config) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void destroy() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}